package com.gxm.练习.多线程;


import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class FutureTaskDemo {
    @Test
    public void test01() throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        long bgn = System.currentTimeMillis();
        List<Future> futures = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            futures.add(executor.submit(new CallAble(String.valueOf(i))));
        }

        for (Future searchResponseFuture: futures){
            while (true) {
                if(searchResponseFuture.isDone()) {
                    System.out.println(searchResponseFuture.get());
                    break;
                } else {
//                    Thread.sleep(100);
                }
            }
        }
        executor.shutdown();
        System.out.println("耗时:" + (System.currentTimeMillis() - bgn)/1000);
    }

    @Test
    public void test02 () {
        MyCallable callable1 = new MyCallable(1000);
        MyCallable callable2 = new MyCallable(2000);

        FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
        FutureTask<String> futureTask2 = new FutureTask<String>(callable2);
        ExecutorService executor = Executors.newFixedThreadPool(3);
//
//        executor.execute(futureTask2);
        for (int i = 0; i < 3; i++) {
            executor.execute(new FutureTask<String>(new MyCallable(i)));
        }


        while (true)
        {
            try {
                if(futureTask1.isDone() && futureTask2.isDone()){
                    System.out.println("Done");
                    //shut down executor service
                    executor.shutdown();
                    return;
                }

                if(!futureTask1.isDone()){
                    //阻塞futureTask1
                    System.out.println("FutureTask1 output="+futureTask1.get());
                }

                if(!futureTask2.isDone()){
                    //阻塞futureTask2
                    System.out.println("FutureTask2 output="+futureTask2.get());
                }

            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }catch(Exception e){
                //do nothing
            }
        }
    }
}

class CallAble implements Callable{
    private String param;

    public CallAble(String param){
        this.param = param;
    }
    @Override
    public Object call() throws Exception {
        Thread.sleep(1000);
        return this.param;
    }
}

class MyCallable implements Callable<String> {

    private long waitTime;

    public MyCallable(int timeInMillis){
        this.waitTime=timeInMillis;
    }
    @Override
    public String call() throws Exception {
        Thread.sleep(waitTime);
        return Thread.currentThread().getName() + "|" + waitTime;
    }

}